package demo;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class UserMapper {
public int insert(User user){
    try (  Connection connection=DBUtil.getConnection();){
      String sql="INSERT INTO user(username,password,nickname,age) " +
              "VALUES(?,?,?,?)";
        PreparedStatement ps=connection.prepareStatement(sql);
        ps.setString(1,user.getUsername());
        ps.setString(2,user.getPassword());
        ps.setString(3,user.getNickname());
        ps.setInt(4,user.getAge());
        return ps.executeUpdate();
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return 0;
}
/*
根据用户名查询用户信息，如果用户不存在，返回null；
 */
public User selectByUsername(String username){
    try (Connection connection=DBUtil.getConnection();){
        String sql="SELECT id,username,password,nickname,age " +
                "FROM user " +
                "WHERE username=?";
        PreparedStatement ps=connection.prepareStatement(sql);
        ps.setString(1,username);
        ResultSet rs=ps.executeQuery();
        if (rs.next()){
            User user=new User();
            user.setUsername(rs.getString("username"));
            user.setPassword(rs.getString("password"));
            user.setNickname(rs.getString("nickname"));
            user.setAge(rs.getInt("age"));
            return user;
        }
    }catch (SQLException e){
        e.printStackTrace();
    }
    return null;
}
public int update(User user){
    try (Connection connection=DBUtil.getConnection();){
        String sql="UPDATE user " +
                "SET password=?,nickname=?,age=? " +
                "WHERE username=?";
        PreparedStatement ps=connection.prepareStatement(sql);
        ps.setString(1,user.getPassword());
        ps.setString(2,user.getNickname());
        ps.setInt(3,user.getAge());
        ps.setString(4,user.getUsername());
        return ps.executeUpdate();//访问修改结果；
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return 0;
}
public List<User> selectAll(){
    List<User> users=new ArrayList<>();
    try (Connection connection=DBUtil.getConnection();){
        String sql="SELECT id,username,password,nickname,age " +
                "FROM user";
       Statement statement =connection.prepareStatement(sql);
        ResultSet rs=statement.executeQuery(sql);
        for (;rs.next();){
            User user=new User();
            user.setUsername(rs.getString("username"));
            user.setPassword(rs.getString("password"));
            user.setNickname(rs.getString("nickname"));
            user.setAge(rs.getInt("age"));
            users.add(user);
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return users;
}
}
